#import "CommonDownloadWebServices.h"
#import "CommonUtil.h"


@implementation CommonDownloadWebServices

@synthesize webData, owner;

- (void)setDelegate:(NSObject<CommonDownloadWebServicesProtocol> *) object {
	owner = object;
}

- (NSDictionary *)getWebServicesData:(NSString *)code type:(NSString *)type {
    //NSLog(@"code:%@,type:%@", code, type);
    [self webServicesRequest:code type:type];
}

- (void)webServicesRequest:(NSString *)code type:(NSString *)type {
	NSString *soapMessage = [NSString stringWithFormat:
                             @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                             "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                             "<soap:Header>\n"
                             "<Authentication>\n"
                             "<username>%@</username>\n"
                             "<password>%@</password>\n"
                             "</Authentication>\n"
                             "</soap:Header>\n"
                             "<soap:Body>\n"
                             "<updateBookInfo xmlns=\"http://www.oz77.com/\">\n"
                             "<in0></in0>\n"
                             "<in1>%@</in1>\n"
                             "<in2>%@</in2>\n"
                             "</updateBookInfo>\n"
                             "</soap:Body>\n"
                             "</soap:Envelope>\n", kWSUsername, kWSPassword, code, type
                             ];
	//NSLog(soapMessage);
	
	//NSURL *url = [NSURL URLWithString:@"http://192.168.1.101:8080/changjiangpress/services/OzService"];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@services/OzService", kServerURL]];
	NSMutableURLRequest *connectionRequest = [NSMutableURLRequest requestWithURL:url];
	NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];
	
	[connectionRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
	[connectionRequest addValue: [NSString stringWithFormat:@"%@services/OzService/updateBookInfo", kServerURL] forHTTPHeaderField:@"SOAPAction"];
	[connectionRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
	[connectionRequest setHTTPMethod:@"POST"];
	[connectionRequest setTimeoutInterval:10.0];
	[connectionRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
	[connectionRequest setCachePolicy:NSURLRequestUseProtocolCachePolicy];
	
	/*请求：同步获取数据
	NSData *data = [NSURLConnection sendSynchronousRequest:connectionRequest
										 returningResponse:nil error:nil];
	
	NSString *str = [[NSString alloc]initWithData: data encoding: NSUTF8StringEncoding];
	NSLog(@">>%@", str);
	 */
	
	//请求：异步获取数据
	NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:connectionRequest delegate:self];
	
	//如果连接已经建好，则初始化data
	if( theConnection ) {
		webData = [[NSMutableData data] retain];
	} else {
		NSLog(@"connection is disabled.");
	}
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	[webData setLength: 0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	[webData appendData:data];
}

//如果电脑没有连接网络，则出现此信息（不是网络服务器不通）
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	[connection release];
	[webData release];
	[owner onCommonDownloadWebServicesFaild:@"didFailWithError"];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	NSString *theXML = [[NSString alloc] initWithBytes:[webData mutableBytes] 
												length:[webData length] 
											  encoding:NSUTF8StringEncoding];
    
    [webData release];
	webData = nil;
    
	//NSLog(@"source DATA:%@", theXML);
	theXML = [theXML stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
	theXML = [theXML stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
	theXML = [theXML stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
	
	@try {
		theXML = [CommonUtil getSubstring:theXML prefix:@"<books>" suffix:@"</books>"];
		//NSLog(@"real DATA:%@\n", theXML);
		//如果不是规则化数据，报错
		if(theXML != nil && [theXML isEqualToString:@"<books>1</books>"] ) {
            [connection release];
            [owner onCommonDownloadWebServicesOver:@"1"];
            return;
        }else{
            [connection release];
			[owner onCommonDownloadWebServicesFaild:@"dataFormatError"];
			return;	
		}
	}
	@catch (NSException *e) {
		//NSLog(@"NSException");
        [connection release];
		[owner onCommonDownloadWebServicesFaild:@"Exception"];
		return;
	}
	//NSLog(@"real DATA:%@", theXML);
	[connection release];
}

@end
